package com.rom.update;

import android.content.Context;
import android.os.RecoverySystem;
import android.util.Log;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CloudRecoverySystem {
    private static File RECOVERY_DIR = new File("/cache/recovery");
    private static final String TAG = "RKRecoverySystem";
    private static File UPDATE_FLAG_FILE = new File(RECOVERY_DIR, "last_flag");

    public static void installPackage(Context context, File packageFile) throws IOException {
        writeFlagCommand(packageFile.getCanonicalPath());
        RecoverySystem.installPackage(context, packageFile);
    }

    public static String readFlagCommand() {
        if (!UPDATE_FLAG_FILE.exists()) {
            return null;
        }
        String str = TAG;
        Log.d(str, "UPDATE_FLAG_FILE is exists");
        char[] buf = new char[128];
        int readCount = 0;
        try {
            readCount = new FileReader(UPDATE_FLAG_FILE).read(buf, 0, buf.length);
            StringBuilder sb = new StringBuilder();
            sb.append("readCount = ");
            sb.append(readCount);
            sb.append(" buf.length = ");
            sb.append(buf.length);
            Log.d(str, sb.toString());
        } catch (IOException e) {
            Log.e(str, "can not read /cache/recovery/last_flag!");
        } catch (Throwable th) {
            UPDATE_FLAG_FILE.delete();
            throw th;
        }
        UPDATE_FLAG_FILE.delete();
        StringBuilder sBuilder = new StringBuilder();
        int i = 0;
        while (i < readCount && buf[i] != 0) {
            sBuilder.append(buf[i]);
            i++;
        }
        return sBuilder.toString();
    }

    public static void writeFlagCommand(String path) throws IOException {
        RECOVERY_DIR.mkdirs();
        UPDATE_FLAG_FILE.delete();
        FileWriter writer = new FileWriter(UPDATE_FLAG_FILE);
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("updating$path=");
            sb.append(path);
            writer.write(sb.toString());
        } finally {
            writer.close();
        }
    }
}
